//
//  PublishController.m
//  soccer
//
//  Created by 上官千城 on 15/9/7.
//  Copyright (c) 2015年 上官千城. All rights reserved.
//

#import "OPublishController.h"

@interface OPublishController ()

@end

@implementation OPublishController



- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationItem.title = @"发布资讯";
    self.photoArray = [NSMutableArray array];
    self.publishText = [NSString string];
    [self layout];
    self.publishInfor = [[OPublishInfo alloc] initWithCallBack:@selector(CallBack:) for:self];
    
}

-(void)layout
{
    //左侧按钮
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button setBackgroundImage:[UIImage imageNamed:@"资讯详情页_18@2x"]forState:UIControlStateNormal];
    [button addTarget:self action:@selector(leftBarButtonItemAction)
     forControlEvents:UIControlEventTouchUpInside];
    button.frame = CGRectMake(0, 0, 40, 40);
    UIBarButtonItem *left = [[UIBarButtonItem alloc] initWithCustomView:button];
    self.navigationItem.leftBarButtonItem = left;
   
    //右侧按钮
    UIButton *button1 = [UIButton buttonWithType:UIButtonTypeCustom];
    [button1 setBackgroundImage:[UIImage imageNamed:@"资讯详情页_18-02@2x"]forState:UIControlStateNormal];
    [button1 addTarget:self action:@selector(rightBarButtonItemAction)
      forControlEvents:UIControlEventTouchUpInside];
    button1.frame = CGRectMake(0, 0, 40, 40);
    UIBarButtonItem *right = [[UIBarButtonItem alloc] initWithCustomView:button1];
    self.navigationItem.rightBarButtonItem = right;
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT) style:UITableViewStyleGrouped];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.view addSubview:self.tableView];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction)];
    [self.tableView addGestureRecognizer:tap];
}

-(void)CallBack:(OBaseLogic *)logic
{
    NSLog(@"OPublish.......%@",self.publishInfor.answerData);
   
}

-(void)tapAction
{
    [[NSNotificationCenter defaultCenter] postNotificationName:@"RETURN" object:nil];
}


-(void)publishText:(NSString *)textOfPub
{
    NSLog(@"imageFinal == %@",self.photoArray);
    NSLog(@"发布信息 == %@",textOfPub);
    self.publishText = textOfPub;
//    获得全局并行队列
      dispatch_queue_t queue =  dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    if (self.photoArray.count == 0 && [textOfPub isEqualToString:@""]) {
        UIAlertView *aler = [[UIAlertView alloc] initWithTitle:@"提示" message:@"内容不能为空" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
        [aler show];
        return;
    } else if (self.photoArray.count == 0 && ![textOfPub isEqualToString:@""]) {
        self.publishInfor.content = textOfPub;
        dispatch_async(queue, ^{
        [self.publishInfor request];
    });
        
    } else if (self.photoArray.count != 0 && [textOfPub isEqualToString:@""]) {
    
        //2.添加任务到队列中，就可以执行任务
             //异步函数：具备开启新线程的能力
        dispatch_async(queue, ^{
            [self upLoadImage:self.photoArray andTextOfPub:textOfPub andUrl:@"http://192.168.1.103:9099/OServer/OAddUserInformation"];
                });
    }
    [DataBaseHandel shareBaseData].dataText = nil;
 [self.navigationController popViewControllerAnimated:YES];
}

//图片上传
-(void)upLoadImage:(NSMutableArray *)imageArray andTextOfPub:(NSString *)textOfPub andUrl:(NSString *)url
{
    //创建管理
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain",@"text/json",@"application/json",@"text/javascript",@"text/html",nil];
    //存放非文件参数
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    if (textOfPub != nil) {
        [params setObject:textOfPub forKey:@"content"];
    } else {
        [params setObject:@"" forKey:@"content"];
    }
   
   //发送请求
    [manager POST:url parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
//        OPublishModel *pubM = [imageArray objectAtIndex:0];
        for (OPublishModel *pubM in imageArray) {
            NSData *fileData = UIImageJPEGRepresentation(pubM.image, 1.0);
                NSLog(@"image = %@,fileName = %@",pubM.image,pubM.fileName);
                 [formData appendPartWithFileData:fileData name:@"headFile" fileName:pubM.fileName mimeType:@"image/jpeg"];
                           };
    } success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"上传成功 response == %@",responseObject);
//        NSDictionary *publishData = responseObject;
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"上传失败 error == %@",error);
    }];
 
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 2 && indexPath.row == 0) {
      NSLog(@"发布");
    }

}


-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0 ) {
    static NSString *cellInfo = @"settingCell";
    OPublishCell *cell = [tableView dequeueReusableCellWithIdentifier:cellInfo];
    if (cell == nil) {
        cell = [[OPublishCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellInfo];
    }
        NSLog(@"---------%ld,%ld",cell.pictureArray.count,self.photoArray.count);
        cell.myDelegate = self;
        cell.pictureArray = self.photoArray;
        
        self.frameForCell = [cell frameForCell];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
    }
    if (indexPath.section == 1) {
        static NSString *cellinfo = @"textCell";
        OPublishCell *cell = [[OPublishCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellinfo];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.myDelegate = self;
        return cell;
    }
    return nil;
}


-(void)deleteImage:(NSMutableArray *)picArray
{
    self.photoArray = picArray;
    [self.tableView reloadData];

}

-(void)pushPhoto
{

    QBImagePickerController *imagePickerController = [[QBImagePickerController alloc] init];
    imagePickerController.delegate = self;
    imagePickerController.allowsMultipleSelection = YES;
    
    
    imagePickerController.limitsMaximumNumberOfSelection = YES;
    imagePickerController.maximumNumberOfSelection = 6 - self.photoArray.count;
    
    
    UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:imagePickerController];
    [self presentViewController:navigationController animated:YES completion:NULL];

}


- (void)imagePickerController:(QBImagePickerController *)imagePickerController didFinishPickingMediaWithInfo:(id)info
{
    if(imagePickerController.allowsMultipleSelection) {
        
        NSArray *mediaInfoArray = (NSArray *)info;
        NSLog(@"Selected %ld photos and mediaInfoArray==%@", mediaInfoArray.count,mediaInfoArray);
        for (NSDictionary *dic in mediaInfoArray) {
            
            OPublishModel *imageM = [[OPublishModel alloc] init];
            
            ALAssetsLibrary* assetslibrary = [[ALAssetsLibrary alloc] init] ;
           
                UIImage *image = [dic objectForKey:UIImagePickerControllerOriginalImage];
                
                NSURL *imageURL = [dic valueForKey:UIImagePickerControllerReferenceURL];
                ALAssetsLibraryAssetForURLResultBlock resultblock = ^(ALAsset *myasset)
                {
                    ALAssetRepresentation *representation = [myasset defaultRepresentation];
                    NSString *fileName = [representation filename];
                 
                    
                    imageM.image = image;
                    imageM.fileName = fileName;
                    
                    [self.photoArray addObject:imageM];
                    NSLog(@"image = %@,fileName = %@",image,fileName);
                    
                };
                
                [assetslibrary assetForURL:imageURL
                               resultBlock:resultblock
                              failureBlock:nil];
            }

        [self.tableView reloadData];

    } else {
        NSDictionary *mediaInfo = (NSDictionary *)info;
        NSLog(@"Selected: %@", mediaInfo);
    }
    
    [self dismissViewControllerAnimated:YES completion:NULL];
}


- (void)imagePickerControllerDidCancel:(QBImagePickerController *)imagePickerController
{
    NSLog(@"取消选择111");
    
    [self dismissViewControllerAnimated:YES completion:NULL];
}


- (NSString *)imagePickerController:(QBImagePickerController *)imagePickerController descriptionForNumberOfPhotos:(NSUInteger)numberOfPhotos
{
    return [NSString stringWithFormat:@"%ld张照片,最多可选%ld张", numberOfPhotos,6 - self.photoArray.count];
}

- (NSString *)imagePickerController:(QBImagePickerController *)imagePickerController descriptionForNumberOfVideos:(NSUInteger)numberOfVideos
{
    return [NSString stringWithFormat:@"视频%ld", numberOfVideos];
}

- (NSString *)imagePickerController:(QBImagePickerController *)imagePickerController descriptionForNumberOfPhotos:(NSUInteger)numberOfPhotos numberOfVideos:(NSUInteger)numberOfVideos
{
    return [NSString stringWithFormat:@"图片%ld 视频%ld", numberOfPhotos, numberOfVideos];
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{

    return 1;

}
//行高
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        return self.frameForCell.size.height + self.frameForCell.origin.y + 10;
    }
    if (indexPath.section == 1) {
        return 300;
    }
    return 50;

}
//右侧按钮使用说明
-(void)rightBarButtonItemAction
{
    OUsageController *view = [[OUsageController alloc]init];
    [self.navigationController pushViewController:view animated:YES];
}
//左侧按钮返回
-(void)leftBarButtonItemAction
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
